package v1

import (
	"RoccBlog/api"
	"RoccBlog/global"
	"RoccBlog/model"
	v1 "RoccBlog/service/v1"
	"github.com/gin-gonic/gin"
	"strconv"
)

type PermissionController struct {
	api.BaseController
	api.BaseOperationController
	Service *v1.PermissionService
}

func init() {
	global.RegisterController(&PermissionController{})
}

func (c *PermissionController) RegisterController(engine *gin.RouterGroup) {
	c.Service = global.GetService(v1.PermissionService{}).(*v1.PermissionService)

	g := engine.Group("/permission")
	{
		g.POST("", c.Add)
		g.DELETE("", c.Remove)
		g.PUT("", c.Modify)
		g.GET("/list", c.Find)
		g.GET("", c.FindById)
	}
}

// Add
// @Tags 权限管理
// @Summary 添加权限
// @Produce  json
// @Param permission body model.Permission required "权限"
// @Success 200 {object} api.Result "成功"
// @Router /permission [post]
func (c *PermissionController) Add(ctx *gin.Context) {
	var permission model.Permission
	if err := ctx.ShouldBind(&permission); err != nil {
		c.ResponseBadRequest(ctx)
		return
	}
	err := c.Service.Add(ctx, permission)

	c.HandleResponseNoResult(ctx, err, "添加权限失败", "添加权限成功")
}

// Remove
// @Tags 权限管理
// @Summary 删除权限
// @Produce  json
// @Param id query int required "权限ID"
// @Success 200 {object} api.Result "成功"
// @Router /permission [delete]
func (c *PermissionController) Remove(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}
	err = c.Service.Remove(ctx, id)

	c.HandleResponseNoResult(ctx, err, "删除权限失败", "删除权限成功")
}

// Modify
// @Tags 权限管理
// @Summary 修改权限
// @Produce  json
// @Param permission body model.Permission required "权限"
// @Success 200 {object} api.Result "成功"
// @Router /permission [put]
func (c *PermissionController) Modify(ctx *gin.Context) {
	var permission model.Permission
	err := ctx.ShouldBind(&permission)
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}
	err = c.Service.Modify(ctx, permission)
	c.HandleResponseNoResult(ctx, err, "修改权限失败", "修改权限成功")
}

// Find
// @Tags 权限管理
// @Summary 权限列表
// @Produce  json
// @Param pageNum query int false "页码"
// @Param pageSize query int false "每页数量"
// @Success 200 {object} api.Result "成功"
// @Router /permission/list [get]
func (c *PermissionController) Find(ctx *gin.Context) {
	pageInfo, err := c.Service.Find(ctx)
	c.HandleResponseResult(ctx, err, "查询权限列表失败", pageInfo)
}

// FindById
// @Tags 权限管理
// @Summary 查找权限by ID
// @Produce  json
// @Param id query int false "权限id"
// @Success 200 {object} api.Result "成功"
// @Router /permission [get]
func (c *PermissionController) FindById(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}
	permission, err := c.Service.FindById(ctx, id)

	c.HandleResponseResult(ctx, err, "查找权限失败", permission)
}
